package cn.jx.asc.config;

import cn.jx.asc.common.jwt.JwtToken;
import cn.jx.asc.common.utils.JwtUtils;
import cn.jx.asc.pojo.entity.User;
import cn.jx.asc.pojo.vo.RoleVO;
import cn.jx.asc.service.RoleService;
import cn.jx.asc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @author lhg
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    /**
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        RoleVO roleVO =null;
        Subject subject = SecurityUtils.getSubject();
        String token = String.valueOf(subject.getPrincipal());
        String username =null;
        if (token ==null){
            log.error("错误访问请求");
            return null;
        }
        username = JwtUtils.getUsername(token);
        if ( username == null){
            log.error("token错误");
        }
        User user = userService.queryUserByName(username);
        if (user ==null){
            log.error("此用户不存在");
        }else {
            roleVO = roleService.queryRoleByUserId(user.getId());
            if (roleVO == null){
                return null;
            }
        }
        String key = roleService.queryRoleKeyById(roleVO.getRoleId());
        info.addRole(key);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        String username = JwtUtils.getUsername(token);

        if (username == null){
            throw new AuthenticationException("token失效");
        }

        User user = userService.queryUserByName(username);
        if (user == null ){
            throw new AuthenticationException("用户不存在");
        }
        if (!JwtUtils.verify(token,username,user.getPassword())){
           throw new AuthenticationException("用户名或者密码错误");
        }

        return new SimpleAuthenticationInfo(token,token,getName());
    }
}
